<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属项目" prop="projectName">
        <el-select v-model="queryParams.projectName" placeholder="请选择所属项目" clearable>
          <el-option v-for="item in projectNameList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="文件名称" prop="fileName">
        <el-input v-model="queryParams.fileName" placeholder="请输入文件名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="文件类型" prop="fileType">
        <el-select v-model="queryParams.fileType" placeholder="请选择文件类型" clearable>
          <el-option v-for="dict in dict.type.file_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="上传人姓名" prop="uploaderName" label-width="120px">
        <el-input v-model="queryParams.uploaderName" placeholder="请输入上传人姓名" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['project:doc:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['project:doc:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['project:doc:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['project:doc:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="docList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column label="文件名称" align="center" prop="fileName" />
      <el-table-column label="文件类型" align="center" prop="fileType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.file_type" :value="scope.row.fileType" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="文件" align="center" prop="fileUrl" /> -->
      <el-table-column label="所属项目" align="center" prop="projectName" />
      <el-table-column label="上传人姓名" align="center" prop="uploaderName" />
      <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['project:doc:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['project:doc:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-download" @click="handleDownload(scope.row)">下载</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改项目文档对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="所属项目" prop="projectName">
          <el-select v-model="form.projectName" placeholder="请选择所属项目" clearable>
            <el-option v-for="item in projectNameList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="文件类型" prop="fileType">
          <el-select v-model="form.fileType" placeholder="请选择文件类型">
            <el-option v-for="dict in dict.type.file_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="文件" prop="fileUrl">
          <file-upload v-model="form.fileUrl" ref="uploader" />
        </el-form-item>

        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDoc, getDoc, delDoc, addDoc, updateDoc } from "@/api/project/doc"
import { listProjectName } from "@/api/project/project"

export default {
  name: "Doc",
  dicts: ['file_type'],
  data() {
    return {
      projectNameList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目文档表格数据
      docList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: null,
        fileType: null,
        uploaderName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectName: [
          { required: true, message: "所属项目不能为空", trigger: "blur" }
        ],
        fileName: [
          { required: true, message: "文件名称不能为空", trigger: "blur" }
        ],
        fileType: [
          { required: true, message: "文件类型不能为空", trigger: "change" }
        ],
      }
    }
  },
  created() {
    this.getList(),//获取所有的项目文件
      this.getProjectNameList()////获取所有的项目名称
  },
  methods: {
    /** 查询项目文档列表 */
    getList() {
      this.loading = true
      listDoc(this.queryParams).then(response => {
        this.docList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询项目名称列表 */
    getProjectNameList() {
      listProjectName().then(response => {
        this.projectNameList = response.data.map(name => ({
          label: name,
          value: name
        }))
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectName: null,
        projectId: null,
        fileName: null,
        fileType: null,
        fileUrl: null,
        uploaderId: null,
        uploaderName: null,
        uploadTime: null,
        remark: null,
        originalFilename: null,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加项目文档"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDoc(id).then(response => {
        const data = response.data
        this.form = data
        // ⭐ 关键：让上传组件拿到 { url, name }，否则就只会显示 url
        if (data.fileUrl) {
          this.form.fileUrl = [{
            url: data.fileUrl,
            name: data.fileName || data.originalFilename || data.fileUrl
          }]
        } else {
          this.form.fileUrl = []
        }
        // 若你希望表单里也保留原始中文名（用于兜底）
        this.form.originalFilename = data.fileName
        this.open = true
        this.title = "修改项目文档"
      })
    },

    // 从子组件读取文件名并写入 form.fileName（多文件用逗号拼）
    syncNamesFromUploader() {
      const up = this.$refs.uploader
      if (!up) return
      const list = Array.isArray(up.fileList) ? up.fileList : []
      if (!list.length) return

      // name 可能为空，兜底用 url 的最后一段
      const names = list.map(f => {
        const n = f.name && String(f.name).trim()
        if (n) return n
        const u = f.url || ''
        const i = u.lastIndexOf('/')
        return i >= 0 ? u.slice(i + 1) : u
      }).join(',')

      this.form.fileName = names
    },
    /** 提交按钮 */
    submitForm() {
      // 先把文件名同步到 form.fileName
      this.syncNamesFromUploader()

      this.$nextTick(() => {
        this.$refs["form"].validate(valid => {
          if (!valid) return

          // 兜底逻辑（若仍无 fileName）
          if (!this.form.fileName) {
            if (this.form.originalFilename) this.form.fileName = this.form.originalFilename
            else if (this.form.fileUrl) {
              const i = this.form.fileUrl.lastIndexOf("/")
              this.form.fileName = i >= 0 ? this.form.fileUrl.slice(i + 1) : this.form.fileUrl
            }
          }

          const req = this.form.id != null ? updateDoc(this.form) : addDoc(this.form)
          req.then(() => {
            this.$modal.msgSuccess(this.form.id != null ? "修改成功" : "新增成功")
            this.open = false
            this.getList()
          })
        })
      })
    },
    watch: {
      'form.fileUrl': {
        handler() { this.$nextTick(() => this.syncNamesFromUploader()) },
        immediate: true
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除项目文档编号为"' + ids + '"的数据项？').then(function () {
        return delDoc(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('project/doc/export', {
        ...this.queryParams
      }, `doc_${new Date().getTime()}.xlsx`)
    },
    handleDownload(row) {
      const urls = this.normalizeUrls(row.fileUrl)
      urls.forEach(u => {
        // 去掉 ? 及其后面内容
        const cleanUrl = u.split('?')[0]
        window.open(cleanUrl, '_blank')  // 或者 location.href = cleanUrl
      })
      console.log("urls:",urls)
    },
    normalizeUrls(fileUrl) {
      if (!fileUrl) return []
      return String(fileUrl).split(',').map(s => s.trim()).filter(Boolean)
    }

  }
}
</script>
